package com.dp.common.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * TODO 创建一个简单的分布式锁
 */
public class SimpleRedisLock implements ILock{

    private final String key_prefix = "lock:";
    private final String ID_prefix = UUID.randomUUID().toString(true) + "-";
    private String name;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取线程标识
        String threadId = ID_prefix + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate
                .opsForValue()
                .setIfAbsent(key_prefix + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }
    /**
     * 释放锁
     */
    @Override
    public void unLock() {
        // 调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(key_prefix + name),
                ID_prefix + Thread.currentThread().getId());
    }

/*
    @Override
    public void unLock() {
        String threadId = ID_prefix + Thread.currentThread().getId();
        // 判断标识是否一致
        String id = stringRedisTemplate.opsForValue().get(key_prefix + name);
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(key_prefix + name);
        }
    }*/
}
